package com.esender.placeorder.config;

import com.esender.placeorder.util.GlobalCache;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        // new 出rabbitTemplate对象
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        // 将connectionFactory设置到rabbitTemplate的对象中
        rabbitTemplate.setConnectionFactory(connectionFactory);
        // 设置confirm回调
        rabbitTemplate.setConfirmCallback(confirmCallback());
        // 设置return回调
        rabbitTemplate.setReturnCallback(returnCallback());
        // 设置mandatory为true
        rabbitTemplate.setMandatory(true);
        // 返回rabbitTemplate对象
        return rabbitTemplate;
    }

    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (null == correlationData) return;
                String msgId = correlationData.getId();
                Object o = GlobalCache.get(msgId);
                System.out.println(o);
                if (ack) {
                    System.out.println("消息发送成功 msgId="+msgId);
                    GlobalCache.remove(msgId);
                } else {
                    System.out.println("消息发送失败 msgId="+msgId);
                    // 这里可以存库记录，然后通过定时任务之类的方式进行重新发送
                }
            }
        };
    }

    public RabbitTemplate.ReturnCallback returnCallback() {
        return new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("消息未路由到队列中");
                System.out.println("return：消息为：" + new String(message.getBody()));
                System.out.println("return：交换机为：" + exchange);
                System.out.println("return：路由为：" + routingKey);
            }
        };
    }
}
